import TauActionPanel from '@/components/TauActionPanel';
import TauPage from '@/components/TauPage';
import TauTable from '@/components/TauTable';
import { useStore } from '@/hooks';
import { Button, Message, Dialog, Drawer } from '@alifd/next';
import { t } from '@lingui/macro';
import { uniqueId } from 'lodash';
import { observer } from 'mobx-react-lite';
import React, { useEffect, useState } from 'react';
import { column, ENUMS } from './stores/definitions';
import { toJS } from 'mobx';
// import BaseModal from './components/BaseModal';
import MoreFuncDropDown from '@/components/MoreFuncDropDown';
import DataForm from './components/DataForm';

const tableId = uniqueId('tauTable-');

const Company = () => {
  const [modal, setModal] = useState({
    show: null,
    record: null,
  });
  const { companyStore: store, ruleStore, loginStore } = useStore();

  useEffect(() => {
    store.search = {
      groupId: ruleStore._group_id,
    };
    // (async () => {
    // })();
  }, [ruleStore._group_id]);

  // 获取列表数据
  const handleOnSearch = (params) => {
    const { getOnDate, ...searchArgs } = params.values;
    const [from, to] = getOnDate || [];
    store.search = {
      from,
      to,
      groupId: ruleStore._group_id,
      ...searchArgs,
    };
  };

  const handleAddMember = () => {
    setModal({ show: 'add', record: null });
  };

  const handleOpenView = (record) => {
    setModal({ show: 'view', record });
  };

  const handleOnEdit = (result) => {
    setModal({ show: 'edit', record: result });
  };

  const handleCancel = () => {
    setModal({ show: null, record: null, type: null });
  };

  const handleOnSubmit = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const { saveVehicle, ...rest } = toJS(result);
        await store.create({ saveVehicle, groupId: ruleStore._group_id }, { ...rest });
        Message.success({ content: t`添加成功` });
      } catch (e) {
        Message.error({ content: t`${e?.source?.message}`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  const handelOnUpdate = async (result) => {
    if (!_.isEmpty(result)) {
      try {
        const { saveVehicle, ...rest } = toJS(result);
        await store.update({ saveVehicle, groupId: ruleStore._group_id }, { ...rest });
        Message.success({ content: t`编辑成功` });
      } catch (e) {
        Message.error({ content: t`${e?.source?.message}`, duration: 7000 });
        throw e;
      }
    }
    handleCancel();
  };

  return (
    <TauPage className="page-container">
      <TauActionPanel
        onSearch={handleOnSearch}
        actions={[
          {
            name: 'btn-member',
            title: t`添加公司`,
            type: 'primary',
            onClick: handleAddMember,
          },
        ]}
        searchItems={
          [
            {
              name: 'getOnDate',
              type: 'date-range',
              props: {
                placeholder: [t`开始创建时间`, t`结束创建时间`],
              },
            },
          ]}
        keywordSearch={{
          // enabled: true,
          placeholder: t`请输入关键字搜索`,
        }}
        className="action-panel"
      />
      <div className="content">
        <TauTable
          instanceId={tableId}
          primaryKey="id"
          tableLayout="fixed"
          currentPage={store.pg.page}
          pageSize={store.pg.size}
          total={store.total}
          onFetch={(pg) => { store.pg = pg; }}
          loading={store.loading}
          dataSource={toJS(store.data)}
          columns={[
            { title: t`序号`, dataIndex: 'idx', width: 44, cell: (v, i) => store.idx(i) },
            column('id', {
              width: 88,
              cell: (v, __, r) => <Button type="primary" text onClick={() => handleOpenView(r)}>{v}</Button>,
            }),
            column('companyName', { width: 88 }),
            column('crDate', { width: 126, sortable: true }),
            {
              title: t`操作`,
              dataIndex: 'memberNumber',
              width: 120,
              cell: (_, __, r) => {
                const data = [
                  {
                    title: t`编辑`,
                    onClick: () => handleOnEdit(r),
                  },
                ];
                return <MoreFuncDropDown dropdownItems={data} maxShow={1} />;
              },
            },
          ]}
        />
      </div>
      {/* <BaseModal
        modal={modal}
        setModal={setModal}
        onCancel={handleCancel}
        onSubmit={modal.show == 'add' ? handleOnSubmit : handelOnUpdate}
        onPass={handleOnPass}
      /> */}
      <Drawer
        visible={modal.show === 'add' || modal.show === 'edit' || modal.show === 'view'}
        title={ENUMS._drawerTitle[modal.show]}
        style={{ maxWidth: '90%' }}
        closeMode={['esc', 'mask', 'close']}
        onClose={() => setModal({ ...modal, toClose: `toClose$${Date.now()}` })}
        width="100%"
      >
        <DataForm
          modal={modal}
          onCancel={handleCancel}
          onSubmit={modal.show == 'add' ? handleOnSubmit : handelOnUpdate}
        />
      </Drawer>
    </TauPage>
  );
};

export default observer(Company);
